<template>
   <div>
        <div class='search'>
            <input v-model="keyWord" class='search-input' type="text" placeholder="输入城市或者拼音">
        </div>
        <!-- 只有当 keyWord 存在的时候，search-content 才显示 -->
        <div  ref="search" class='search-content' v-show="keyWord">
                <ul>
                    <li  v-for='item of list' :key='item.id' 
                    class='searc-item border-bottom'
                     @click='handleChangeCity(item.name)'
                    >{{item.name}}</li>
                    <li class='searc-item border-bottom' v-show="hasNoData">
                         没有找到匹配数据
                    </li>
                </ul>
        </div>
        
   </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default{
    name:'CitySearch',
    props: {
        citys:Object
    },
    data () {
        return {
            keyWord:'',
            list:[],
            timer:'',
        }
    },
     //当搜索框没有 匹配到合适内容的时候  显示li没有找到匹配数据
    computed :{
      hasNoData () {
        return !this.list.length
      }
    },
    //下拉滚动
    mounted () {
        this.scroll = new BScroll(this.$refs.search)
    },
    watch:{
        keyWord () {
            if(!this.keyWord){
                this.list = []
                return
            }
            if(this.timer){
                clearTimeout(this.timer)
            }
            // i  就是citys  中的[A , B, C, ----,Z]
            // value  是citys 中的 {'id':'122','spell':'beijing','name':'北京'}
            this.timer = setTimeout(() => {
                const result = [];
                for(let i in this.citys){               
                    this.citys[i].forEach ((value) => {
                        if(value.spell.indexOf (this.keyWord) > -1 || value.name.indexOf (this.keyWord) > -1){
                            result.push(value)
                        }
                    }); 
                }
                this.list = result
            },100)
        }
    },
    methods: {
        handleChangeCity (city) { 
           this.changeCity(city)
                this.$router.push('/')
           },
           //意思是我们有一个mutation叫做changeCity 。然后我们mutation 映射到这个组件里面一个叫做changeCity 的方法里
           ...mapMutations(['changeCity'])
    },
}
</script>  

<style lang="stylus" scoped>
@import '~@styles/varibles.styl'
.search 
 height 0.72rem
 padding 0.1rem
 background-color $bgColor

.search-input
 box-sizing border-box
 width 100%
 height 0.62rem
 line-height 0.62rem
 text-align center
 padding 0.1rem
 border-radius 0.06rem
 color #666

.search-content
 overflow hidden
 position absolute
 top 1.8rem
 left 0
 right 0
 bottom 0
 background-color #eeeeee
 z-index 88

.searc-item
 line-height 0.5rem
 background-color #ffffff
 text-align left 
 padding .2rem

</style>